package cn.com.controller;

import cn.com.entity.CompanyMember;
import cn.com.service.CompanyService;
import cn.com.util.CompanyMemberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Controller
public class ManagerController {
    @Autowired
    private CompanyService companyService;


    @RequestMapping("/fileUpload.do")
    public ModelAndView uploadFile(HttpSession session, HttpServletRequest request){
        Long startTime = System.currentTimeMillis();
        ModelAndView mav = new ModelAndView();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(session.getServletContext());

        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest =(MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path="E:/springUpload"+file.getOriginalFilename();
                    System.out.println(path);
                    try {
                        //上传
                        file.transferTo(new File(path));
                    }catch (IOException e){
                        System.out.print("上传失败");
                    }
                    //上传成功后读取  excek
                    path = path.replaceAll("/","\\\\\\\\");
                    System.out.println(path);
                    List<CompanyMember> companyMemberList = CompanyMemberUtil.getAllCompanyMemberFormExcel(path);
                    if(companyMemberList!=null){
                        mav.addObject("companyMemberList",companyMemberList);
                        companyService.saveCompanyMemberList(companyMemberList);
                    }
                }

            }
            Long endTime = System.currentTimeMillis();

        }

        mav.setViewName("index");
        return  mav;

    }
}
